import { IconButton } from "@/components/icon";
import { Iconify } from "@/components/icon";
import { Project, projectService } from "@/api/services/projectService";
import {
	Button,
	Card,
	Space,
	Table,
	Tag,
	Tooltip,
	Typography,
	Modal,
	message,
	Form,
	Input,
	Select,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import dayjs from "dayjs";

const { TextArea } = Input;

const statusMap = {
	0: { text: "禁用", color: "error" },
	1: { text: "启用", color: "success" },
};

export default function ProjectListPage() {
	const [loading, setLoading] = useState(false);
	const [records, setRecords] = useState<Project[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [modalVisible, setModalVisible] = useState(false);
	const [modalTitle, setModalTitle] = useState("新增项目");
	const [editingRecord, setEditingRecord] = useState<Project>();
	const [form] = Form.useForm();

	const fetchRecords = async (page = 1, limit = 10) => {
		setLoading(true);
		const res = await projectService.projectList({ page, limit });
		setRecords(res.items);
		setTotal(res.total);
		setLoading(false);
	};

	useEffect(() => {
		fetchRecords(currentPage, pageSize);
	}, [currentPage, pageSize]);

	const handleAdd = () => {
		setModalTitle("新增项目");
		setEditingRecord(undefined);
		form.resetFields();
		setModalVisible(true);
	};

	const handleEdit = (record: Project) => {
		setModalTitle("编辑项目");
		setEditingRecord(record);
		form.setFieldsValue(record);
		setModalVisible(true);
	};

	const handleDelete = (record: Project) => {
		Modal.confirm({
			title: "确认删除",
			content: "确定要删除该项目吗？",
			onOk: async () => {
				try {
					const res = await projectService.projectDelete(record.id);
					message.success("删除成功");
					fetchRecords(currentPage, pageSize);
				} catch (error) {
					message.error("删除失败");
				}
			},
		});
	};

	const handleChangeStatus = async (record: Project) => {
		try {
			const res = await projectService.projectChangeStatus(
				record.id,
				record.status === 1 ? 0 : 1,
			);
			message.success("状态修改成功");
			fetchRecords(currentPage, pageSize);
		} catch (error) {
			message.error("状态修改失败");
		}
	};

	const handleSubmit = async () => {
		try {
			const values = await form.validateFields();
			let res;
			if (editingRecord) {
				res = await projectService.projectEdit(editingRecord.id, values);
			} else {
				res = await projectService.projectAdd(values);
			}
			message.success(editingRecord ? "更新成功" : "添加成功");
			fetchRecords(currentPage, pageSize);
			setModalVisible(false);
		} catch (error) {
			message.error(editingRecord ? "更新失败" : "添加失败");
		}
	};

	const columns: ColumnsType<Project> = [
		{
			title: "项目名称",
			dataIndex: "name",
			width: 200,
			render: (text, record) => (
				<div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
					<Typography.Text strong>{text}</Typography.Text>
					{record.url && (
						<Typography.Link
							href={record.url}
							target="_blank"
							style={{ fontSize: "12px" }}
						>
							{record.url}
						</Typography.Link>
					)}
				</div>
			),
		},
		{
			title: "状态",
			dataIndex: "status_text",
			width: 100,
			render: (text, record) => (
				<Tag color={statusMap[record.status]?.color}>
					{text || statusMap[record.status]?.text}
				</Tag>
			),
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			width: 180,
			render: (createtime) => (
				<span>{dayjs(createtime * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
			),
		},
		{
			title: "更新时间",
			dataIndex: "updatetime",
			width: 180,
			render: (updatetime) => (
				<span>{dayjs(updatetime * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
			),
		},
		{
			title: "操作",
			key: "action",
			width: 180,
			render: (_, record) => (
				<Space>
					<Tooltip title="编辑">
						<IconButton onClick={() => handleEdit(record)}>
							<Iconify icon="material-symbols:edit-outline" />
						</IconButton>
					</Tooltip>
					{/* <Tooltip title={record.status === 1 ? "禁用" : "启用"}>
						<IconButton onClick={() => handleChangeStatus(record)}>
							<Iconify
								icon={
									record.status === 1
										? "material-symbols:block"
										: "material-symbols:check-circle-outline"
								}
							/>
						</IconButton>
					</Tooltip> */}
					<Tooltip title="删除">
						<IconButton onClick={() => handleDelete(record)}>
							<Iconify icon="material-symbols:delete-outline" />
						</IconButton>
					</Tooltip>
				</Space>
			),
		},
	];

	return (
		<div style={{ padding: "24px", background: "#f5f5f5", minHeight: "100vh" }}>
			<Card bordered={false} style={{ borderRadius: "12px" }}>
				<div
					style={{
						marginBottom: "24px",
						display: "flex",
						alignItems: "center",
						justifyContent: "space-between",
					}}
				>
					<Typography.Title level={4} style={{ margin: 0 }}>
						项目管理
					</Typography.Title>
					<Button
						type="primary"
						icon={<Iconify icon="material-symbols:add" />}
						onClick={handleAdd}
					>
						新增项目
					</Button>
				</div>

				<Table
					rowKey="id"
					columns={columns}
					dataSource={records}
					loading={loading}
					pagination={{
						current: currentPage,
						pageSize,
						total,
						onChange: (page, size) => {
							setCurrentPage(page);
							setPageSize(size);
						},
						style: { marginTop: "24px" },
					}}
					scroll={{ x: 800 }}
				/>
			</Card>

			<Modal
				title={
					<div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
						<Iconify
							icon={
								editingRecord
									? "material-symbols:edit-outline"
									: "material-symbols:add"
							}
						/>
						<span>{modalTitle}</span>
					</div>
				}
				open={modalVisible}
				onCancel={() => setModalVisible(false)}
				onOk={handleSubmit}
				width={600}
			>
				<Form
					form={form}
					layout="vertical"
					initialValues={{ status: 1 }}
					style={{ padding: "24px 0" }}
				>
					<Form.Item
						name="name"
						label="项目名称"
						rules={[{ required: true, message: "请输入项目名称" }]}
					>
						<Input placeholder="请输入项目名称" />
					</Form.Item>

					<Form.Item name="url" label="项目地址">
						<Input placeholder="请输入项目地址" />
					</Form.Item>

					<Form.Item
						name="status"
						label="状态"
						rules={[{ required: true, message: "请选择状态" }]}
					>
						<Select>
							<Select.Option value={1}>启用</Select.Option>
							<Select.Option value={0}>禁用</Select.Option>
						</Select>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
}
